import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:myapp/app/theme/app_color.dart';

class SliderBanner extends StatefulWidget {
  final List<String> list;

  SliderBanner(this.list);

  @override
  _SliderBannerState createState() => _SliderBannerState();
}

class _SliderBannerState extends State<SliderBanner> {
  _SliderBannerState() {}

  final PageController _pageController = PageController();

  int _length = 0;

  int _index = 0;

  final int _step = 1500;

  int _indicator = 0;

  late Timer _timer;

  @override
  void initState() {
    _length = widget.list.length;
    print("_SliderBannerState ${_length}");
    _timer = Timer.periodic(Duration(milliseconds: _step), (timer) {
      print("periodic ${_length}");
      if (_length == 0) return;
      _indicator = (_index + 1) % _length;
      print("${_indicator}");
      _pageController.animateToPage(_indicator, duration: Duration(milliseconds: 500), curve: Curves.easeInCirc);
    });
    super.initState();
  }

  @override
  void dispose() {
    _timer.cancel();
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: AspectRatio(
        child: Stack(
          children: [
            PageView(
              onPageChanged: (position){
                setState(() {
                  _index = position;
                });
              },
              controller: _pageController,
              children: widget.list
                  .map((e) => Container(
                        child: ClipRRect(
                          child: Image.network(
                            e,
                            fit: BoxFit.fitWidth,
                          ),
                          borderRadius: BorderRadius.circular(5),
                        ),
                        margin: EdgeInsets.only(left: 16, right: 16),
                      ))
                  .toList(),
            ),
            Positioned(
              bottom: 15,
              right: 30,
              child: Row(
                children: widget.list
                    .asMap()
                    .keys
                    .map((e) => Container(
                          width: 8,
                          height: 8,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(4),
                            color:
                                e == _index ? AppColor.white : AppColor.white50,
                          ),
                          margin: EdgeInsets.only(left: 3, right: 3),
                        ))
                    .toList(),
              ),
            ),
          ],
        ),
        aspectRatio: 16.0 / 6,
      ),
    );
  }
}
